package com.jindianjichi.auth.domain.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jindianjichi.auth.common.enums.IsDeletedEnum;
import com.jindianjichi.auth.domain.BO.AuthPermissionBO;
import com.jindianjichi.auth.domain.convert.AuthPermissionBoConvert;
import com.jindianjichi.auth.domain.redis.RedisUtil;
import com.jindianjichi.auth.domain.service.AuthPermissionDomainService;
import com.jindianjichi.auth.infra.basic.entity.AuthPermission;
import com.jindianjichi.auth.infra.basic.service.AuthPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {
    @Autowired
    private AuthPermissionService authPermissionService;
    @Autowired
    private RedisUtil redisUtil;


    private String authPermissionPrefix = "auth.permission";

    @Override
    public Boolean add(AuthPermissionBO permissionBO) {
        AuthPermission authPermission = AuthPermissionBoConvert.instance.convertToBoAuthPermission(permissionBO);
        authPermission.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        int count = authPermissionService.insert(authPermission);
        return count > 0;
    }

    /**
     * 修改权限
     *
     * @param permissionBO
     * @return
     */
    @Override
    public Boolean update(AuthPermissionBO permissionBO) {
        AuthPermission authPermission = AuthPermissionBoConvert.instance.convertToBoAuthPermission(permissionBO);
        int count = authPermissionService.update(authPermission);
        return count > 0;
    }

    /**
     * 删除权限
     *
     * @param permissionBO
     * @return
     */
    @Override
    public Boolean delete(AuthPermissionBO permissionBO) {
        AuthPermission authPermission = AuthPermissionBoConvert.instance.convertToBoAuthPermission(permissionBO);
        authPermission.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        int count = authPermissionService.update(authPermission);
        return count > 0;
    }

    @Override
    public List<String> getPermission(String userName) {
        String permissionKey = redisUtil.buildKey(authPermissionPrefix, userName);
        //查询角色对应的权限
        String permission = redisUtil.get(permissionKey);
        if (!StringUtils.isNotBlank(permission)) {
            return Collections.emptyList();
        }
        List<AuthPermission> authPermissionList = new Gson().fromJson(permission, new TypeToken<List<AuthPermission>>() {
        }.getType());
        List<String> list = authPermissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        return list;
    }
}